<template>
  <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
    <el-tree :data="tree" ref="tree" show-checkbox node-key="id" default-expand-all :default-checked-keys="checkTree"></el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addPer">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { allPer,addPer,currentRoleWithPres } from "./api";
export default {
  data() {
    return {
      dialogVisible: false,
      tree: [],
      checkTree:[],
      roleId:null
    };
  },
  methods: {
    build(item) {
      const obj = {};
      obj.id = item.id;
      obj.label = `${item.perkey}(${item.nameZh})`;
      return obj;
    },
    getAllTree(id) {
      this.tree = [];
      allPer().then(v => {
        if (v.ok) {
          const roots = v.data.reduce((pre, val, arr) => {
            let perkey = val.perkey.split("_")[0];
            if (!pre.includes(perkey)) {
              pre.push(perkey);
              return pre;
            } else {
              return pre;
            }
          }, []);
          roots.forEach(el => {
            const obj = {};
            const children = v.data
              .filter(t => new RegExp("^" + el).test(t.perkey))
              .map(t => this.build(t));
            obj.id = el;
            obj.label = el;
            obj.children = children;
            this.tree.push(obj);
          });
          this.currentRoleWithPres(id);
        }
        
      });
    },
    addPer(){
      const keys = this.$refs.tree.getCheckedKeys()
      addPer(this.roleId,keys.filter(t=>/[0-9]+/.test(t))).then(v=>{
          if(v.ok){
              this.$message.success('操作成功')
          }else{
              this.$message.error(v.msg||'操作失败')
          }
      }).finally(()=>{
          this.dialogVisible = false;
      })
      
    },
    currentRoleWithPres(id){
      currentRoleWithPres(id).then(v=>{
         if(v.ok){
             this.checkTree = v.data
         }
      })
    },
    showModal(id) {
        this.roleId = id
      this.dialogVisible = true;
      this.getAllTree(id);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
  }
};
</script>

<style>
</style>